//
//  MNDMyIntegralViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/16.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDMyIntegralViewController.h"
#import "WMPanGestureRecognizer.h"
#import "MNDIntegralDetailViewController.h"
#import "MNDIntegralExchangeViewController.h"
#import "MNDExchangeAlertViewController.h"
#import "MNDWebViewController.h"
#import "MNDMunityLevelModel.h"
#import "MNDLoginUserModel.h"
@interface MNDMyIntegralViewController ()
@property (nonatomic, strong) NSArray *itemArray;
@property (nonatomic, strong) WMPanGestureRecognizer *panGesture;
@property (nonatomic, assign) CGPoint lastPoint;
@property (weak, nonatomic) IBOutlet UIView *toyScoreView;
@property (nonatomic, strong)MNDExchangeAlertViewController *alertVC;
@property (strong, nonatomic)MNDMunityLevelModel *munityLevelModel;
@end

@implementation MNDMyIntegralViewController

- (NSArray<NSString *> *)titles {
    return @[@"积分明细",@"兑换记录"];
}

- (instancetype)init {
    
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"PomelCircle" bundle:nil];
    self = [storyBoard instantiateViewControllerWithIdentifier:@"MNDMyIntegralViewController"];
    self.menuItemWidth = kScreenWidth*0.5;
    self.menuHeight = 48;
    self.menuViewBottomSpace = 1;
    self.menuViewStyle = WMMenuViewStyleLine;
    self.titleSizeSelected = 15.0;
    self.titleSizeNormal = 15.0;
    self.titleColorNormal = [UIColor blackColor];
    self.titleColorSelected = [UIColor colorWithRed:237/255.0 green:129/255.0 blue:100/255.0 alpha:1.0];
    self.menuBGColor = [UIColor whiteColor];
    self.viewTop = kWMHeaderViewHeight + kNavigationBarHeight;
    self.viewFrame = CGRectMake(0,kWMHeaderViewHeight + kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self loadData];
    self.view.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    self.panGesture = [[WMPanGestureRecognizer alloc] initWithTarget:self action:@selector(panOnView:)];
    [self.view addGestureRecognizer:self.panGesture];
    self.myTotalScoreLabel.text = self.myTotalScore;
    
    [self initialBarbuttonItems];
    
    //监听通知dismissAlert
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissAlertVC:) name:@"dismissAlertVC" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (![MNDLoginUserModel isUserLogin]) {
        [UserDefaultsTool removeForKey:kForgetGesture];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }

}
- (void)dismissAlertVC:(NSNotification *)notification {
    [self loadData];
    self.selectIndex = 1;
    [[NSNotificationCenter defaultCenter] postNotificationName: @"showExchangeRecord"object:nil];
    UIView *springView = self.alertVC.view;
    [springView removeFromSuperview];
    [self.alertVC removeFromParentViewController];
}


- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"积分规则"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(clickScoreRegularBtn:)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)loadData {
    //积分及头像获取
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_POMELCIRCLE_LEVEL parameters:[MNDSign signedParamWithDict:@{@"user_code": user.user_code}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            NSLog(@"%@",responseModel.data);
            weakself.munityLevelModel = [MNDMunityLevelModel mj_objectWithKeyValues:responseModel.data];
            [weakself configMyInfoContent];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configMyInfoContent {
    self.myTotalScoreLabel.text = self.munityLevelModel.user_enable_integral;
}

//点击积分规则
- (void)clickScoreRegularBtn:(UIBarButtonItem *)sender {
    MNDWebViewController *webVC = [[MNDWebViewController alloc]init];
    webVC.naviBarHidden = YES;
    webVC.webViewUrl = [NSString stringWithFormat:@"%@%@", WebBaseURL, kScoreRegular];
    webVC.isFromIntegral = YES;
    webVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webVC animated:YES];
}

//兑换积分
- (IBAction)clickExchangeScoreButton:(UIButton *)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDExchangeAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDExchangeAlertViewController"];
    __weak UIView *springView = alertVC.view;
    self.alertVC = alertVC;
    alertVC.myTotalScore = self.myTotalScore;
    alertVC.canUseScoreLabel.text = [NSString stringWithFormat:@"可用积分:%@",self.myTotalScore];
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
//    __weak typeof(self) weakSelf = self;
    [alertVC.closeScoreButton bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
//        [springView removeFromSuperview];
//        [alertVC removeFromParentViewController];
    } forControlEvents:UIControlEventTouchUpInside];
    
    
}


//手势滑动
- (void)panOnView:(WMPanGestureRecognizer *)recognizer {
    NSLog(@"pannnnnning received..");
    
    CGPoint currentPoint = [recognizer locationInView:self.view];
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.lastPoint = currentPoint;
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {
        
        CGPoint velocity = [recognizer velocityInView:self.view];
        CGFloat targetPoint = velocity.y < 0 ? kNavigationBarHeight : kNavigationBarHeight + kWMHeaderViewHeight;
        NSTimeInterval duration = fabs((targetPoint - self.viewTop) / velocity.y);
        
        if (fabs(velocity.y) * 1.0 > fabs(targetPoint - self.viewTop)) {
            NSLog(@"velocity: %lf", velocity.y);
            [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.viewTop = targetPoint;
                self.toyScoreView.transform = CGAffineTransformMakeTranslation(0, -(64+160+20-self.viewTop));
            } completion:nil];
            
            return;
        }
        
    }
    
    CGFloat yChange = currentPoint.y - self.lastPoint.y;
    self.viewTop += yChange;
    self.toyScoreView.transform = CGAffineTransformMakeTranslation(0, -(64+160+20-self.viewTop));
    self.lastPoint = currentPoint;
}


- (void)setViewTop:(CGFloat)viewTop {
    
    _viewTop = viewTop;
    
    if (_viewTop <= kNavigationBarHeight) {
        _viewTop = kNavigationBarHeight;
    }
    
    if (_viewTop > kWMHeaderViewHeight + kNavigationBarHeight) {
        _viewTop = kWMHeaderViewHeight + kNavigationBarHeight;
    }
    
    self.viewFrame = CGRectMake(0, _viewTop, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
}


- (NSInteger)numbersOfChildControllersInPageController:(WMPageController *)pageController {
    return self.titles.count;
}

- (UIViewController *)pageController:(WMPageController *)pageController viewControllerAtIndex:(NSInteger)index {
    if (index == 0) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"PomelCircle" bundle:nil];
        MNDIntegralDetailViewController *integralDetailVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDIntegralDetailViewController"];
        return integralDetailVC;
    }else {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"PomelCircle" bundle:nil];
         MNDIntegralExchangeViewController *integralExchangeVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDIntegralExchangeViewController"];
        return integralExchangeVC;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
